<template>
  <view class="index_item_box">
    <!-- 一级类目 -->
    <!-- <view class="category_top" id="category_top">
      <scroll-view scroll-x="true" class="scroll" :scroll-left="scrollX" :scroll-with-animation="true">
        <block>
          <view v-for="(item, key, index) in materialIds" :key="index" @click="choosenCategory(materialIds[key], key, index)" class="item"
            :class="materialIds[key] === param.materialId ? 'active' : ''">
            <text class="title">{{key}}</text>
          </view>
        </block>
      </scroll-view>
    </view> -->
    <ItemListComp class="item_box" v-if="questionList.length > 0" :questionList="questionList" :userInfo="userInfo" />
    <view class="cu-load bg-grey" v-if="isLoad" :class="finished?'over':'loading'"></view>
    <!-- 占位用，切换类目防止页面跳动 -->
    <view class="block" v-if="!questionList || questionList.length <= 0"></view>
  </view>
</template>

<script>
  import crypto from 'crypto'
  import ItemListComp from '@/pages/pagecomponents/itemlist'
  export default {
    components: {
      ItemListComp
    },
    data() {
      return {
        questionList: [],
        advertiseList: [],
        scrollX: 0, // scroll窗口向左偏移的距离
        scrollY: 0, // 点击一级类目需要滚动的距离
        currentAdNumber: 0, // 已经加入的广告位数,用于消除数组长度的影响
        materialIds: {"好券直播":3756,"猜你喜欢":6708,"食品":3761,"美妆":3763,"母婴":3760,"女装":3767,"家居家装":3758,"数码家电":3759,"运动户外":3766,"内衣":3765,"男装":3764,"鞋包配饰":3762},
        param: {
          pageId: 1,
          pageSize: 10,
          materialId: 3756, // 物料ID
        },
        isLoad: false,
        finished: false,
      }
    },
    computed:{
      userInfo(){
        return this.$store.state.userInfo
      },
    },
    created() {
      // #ifndef APP-PLUS
      this.getItemList()
      // #endif
      // #ifdef APP-PLUS
      plus.device.getInfo({ // 获取IMEI
        success: e =>{
          let imei=e.imei.split(',')[0];
          let hash = crypto.createHash('md5')
          hash.update(imei)
          let imeiMd5 = hash.digest('hex')
          this.param.device_encrypt = 'MD5' // 智能匹配-设备号加密类型：MD5
          this.param.device_type = 'IMEI' // 智能匹配-设备号类型：IMEI，或者IDFA，或者UTDID（UTDID不支持MD5加密）
          this.param.device_value = imeiMd5 // 智能匹配-设备号加密后的值（MD5加密需32位小写）
          this.getItemList()
        },
        fail: e => {
          this.getItemList()
          uni.showToast({
            icon: 'none',
            title: '您已残忍拒绝授权',
          })
        }
      })
      // #endif
    },
    mounted(){
      // #ifdef APP-PLUS
      const query = uni.createSelectorQuery().in(this);
      query.select('#category_top').boundingClientRect(data => {
        this.scrollY = data.top;
      }).exec();
      // #endif
    },
    methods: {
      choosenCategory(materialId, key, index) {
        // 点击一级类目
        // #ifndef H5 || APP-PLUS
        getApp().mtj.trackEvent('category', { // 埋点统计
          category_name: key,
          user_id: this.userInfo.id || 0,
        });
        // #endif
      
        // 自动滚动 start
        let scrollX = 0;
        for(let keyValue in this.materialIds){
          if(keyValue === key){
            break
          }
          scrollX += keyValue.length * 10
        }
        this.scrollX = scrollX
        // 自动滚动 end
      
        this.param.materialId = materialId;
        this.getItemList("pullDown");
        // #ifdef APP-PLUS
        uni.pageScrollTo({ // 滚动到顶部
          scrollTop: this.scrollY
        });
        // #endif
        // #ifndef APP-PLUS
        uni.pageScrollTo({ // 滚动到顶部
          scrollTop: 281
        });
        // #endif
      },
      nextPaging() {
        // 下一页
        if (this.finished !== true) {
          this.param.pageId += 1
          this.getItemList()
        }
      },
      insertAdvertise() {
        if(this.param.materialId === 3756){ // 只有好券直播需要插播广告
          this.advertiseList.forEach(item => {
            // 将当前页数广告位插入
            if (item.line <= this.param.pageSize * this.param.pageId / 2 && item.line > this.param.pageSize *
              (this.param.pageId - 1) / 2) {
              let questionList = this.questionList
              // 此处需要减去已加入的广告位，对数组长度的影响
              questionList.splice((item.line - 1) * 2 - this.currentAdNumber, 0, item)
              this.questionList = questionList
              this.currentAdNumber += 1
            }
          })
        }
      },
      getAdvertise() {
        // 获取广告位
        this.$api.user.getAdvertiseByType({
          type: 2, // 广告位类型:1轮播，2商品内部
        }).then(res => {
          // 存储广告位数组
          this.advertiseList = res.data.list
          this.insertAdvertise()
        })
      },
      getItemList(type) {
        if (type === 'pullDown') {
          // 下拉刷新
          this.advertiseList = [], // 广告列表
          this.currentAdNumber = 0, // 当前插入的广告数
          this.isLoad = true
          this.questionList = []
          this.param.pageId = 1
        }
        this.isLoad = true
        this.$api.user.materialList(this.param).then(res => {
          if (type === 'pullDown') {
            // 下拉刷新
            uni.stopPullDownRefresh();
          }
          this.isLoad = false
          if (res.data.list && res.data.list.length <= 0) {
            this.finished = true;
          }
          let imgList = res.data.list
          let questionList = this.questionList
          questionList = questionList.concat(imgList)
          this.questionList = questionList
          
          if (this.param.pageId === 1) {
            // 第一页获取商品广告位
            this.getAdvertise()
          }else{
            this.insertAdvertise()
          }
        })
      },
    }
  }
</script>

<style scoped lang="scss">
  .index_item_box {
    .category_top {
      // position: fixed;
      // top: 49px; // 防止出现空隙
      // left: 0;
      // right: 0;
      position: sticky;
      position: -webkit-sticky;    // 兼容 -webkit 内核的浏览器
      top: 0px; // 必须设一个值，否则不生效
      padding: 0 20upx;
      z-index: 2000;
      background: #ffffff;
      .scroll {
        width: 100%;
        white-space: nowrap;
        padding: var(--status-bar-height) 0 0;
        .item {
          display: inline-block;
          line-height: 80upx;
          +.item {
            margin-left: 32upx;
          }
        }
        .active {
          color: #4b6c92;
          font-weight: 600;
          border-bottom: 2px solid #4b6c92;
        }
      }
    }
    .item_box {
      min-height: 800px;
    }
    .block{
      height: 900px;
    }
    .cu-load::before {
      content: none
    }
  }
</style>
